<template>
  <div class="search-tab">
    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Search /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ totalSearches }}</div>
              <div class="stat-label">总搜索次数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Bell /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ subscribedCount }}</div>
              <div class="stat-label">订阅关键词</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ latestSearchTime }}</div>
              <div class="stat-label">最近搜索</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和操作 -->
    <div class="filter-section">
      <el-row :gutter="16" align="middle">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            :placeholder="activeTab === 'history' ? '搜索关键词' : '搜索名称'"
            clearable
            prefix-icon="Search"
            size="small"
          />
        </el-col>
        <el-col :span="4" v-if="activeTab === 'history'">
          <el-select v-model="selectedSite" placeholder="选择站点" size="small" clearable>
            <el-option label="全部站点" value="" />
            <el-option label="雅虎闲置" value="yahoo" />
            <el-option label="煤炉闲置" value="mercari" />
            <el-option label="乐天市场" value="rakuten" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-select v-model="subscribeStatus" placeholder="订阅状态" size="small" clearable>
            <el-option label="全部状态" value="" />
            <el-option label="已订阅" value="已订阅" />
            <el-option label="未订阅" value="未订阅" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="exportSearches">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
        <el-col :span="6">
          <!-- 清空记录功能已删除 -->
        </el-col>
      </el-row>
    </div>

    <!-- Tabs：历史搜索 / 我的筛选 -->
    <el-tabs v-model="activeTab" class="search-tabs">
      <el-tab-pane label="历史搜索" name="history">
        <div class="search-section">
          <div class="section-header">
            <div class="section-title">
              <el-icon><Timer /></el-icon>
              <span>历史搜索</span>
            </div>
            <div class="section-count">共 {{ filteredHistorySearch.length }} 条记录</div>
          </div>
          <el-table 
            :data="historyPaged" 
            border 
            stripe 
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            row-class-name="search-row"
          >
            <el-table-column prop="idx" label="序号" width="80" align="center" />
            <el-table-column label="站点信息" width="140">
              <template #default="scope">
                <div class="site-info">
                  <el-tag :type="getSiteTagType(scope.row.site)" size="small">
                    {{ getSiteDisplayName(scope.row.site) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="搜索关键词" min-width="200">
              <template #default="scope">
                <div class="keyword-info">
                  <div class="keyword-text">{{ scope.row.name }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订阅状态" width="120">
              <template #default="scope">
                <div class="subscribe-status">
                  <el-tag :type="scope.row.subscribe === '已订阅' ? 'success' : 'info'" size="small">{{ scope.row.subscribe }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="添加时间" width="180">
              <template #default="scope">
                <div class="time-info">
                  <div class="time-date">{{ formatDate(scope.row.time) }}</div>
                  <div class="time-hour">{{ formatTime(scope.row.time) }}</div>
                  <div class="time-ago">{{ getTimeAgo(scope.row.time) }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-section">
            <el-pagination
              v-model:current-page="historyPage"
              :page-size="PAGE_SIZE"
              :total="filteredHistorySearch.length"
              layout="total, prev, pager, next"
            />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="我的筛选" name="myFilters">
        <div class="search-section">
          <div class="section-header">
            <div class="section-title">
              <el-icon><Clock /></el-icon>
              <span>我的筛选</span>
            </div>
            <div class="section-count">共 {{ filteredRecentSearch.length }} 条记录</div>
          </div>
          <el-table 
            :data="filtersPaged" 
            border 
            stripe 
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            row-class-name="search-row"
          >
            <el-table-column prop="idx" label="序号" width="80" align="center" />
            <el-table-column label="搜索名称" min-width="200">
              <template #default="scope">
                <div class="search-name">
                  <div class="name-text">{{ scope.row.name }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="搜索条件" min-width="300">
              <template #default="scope">
                <div class="condition-info">
                  <div class="condition-text">{{ scope.row.condition }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订阅状态" width="120">
              <template #default="scope">
                <div class="subscribe-status">
                  <el-tag :type="scope.row.subscribe === '已订阅' ? 'success' : 'info'" size="small">{{ scope.row.subscribe }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="添加时间" width="180">
              <template #default="scope">
                <div class="time-info">
                  <div class="time-date">{{ formatDate(scope.row.time) }}</div>
                  <div class="time-hour">{{ formatTime(scope.row.time) }}</div>
                  <div class="time-ago">{{ getTimeAgo(scope.row.time) }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-section">
            <el-pagination
              v-model:current-page="filtersPage"
              :page-size="PAGE_SIZE"
              :total="filteredRecentSearch.length"
              layout="total, prev, pager, next"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, computed, watch } from 'vue';
import { 
  Search, 
  Bell, 
  Clock, 
  Download, 
 Timer
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps<{ historySearch: any[]; recentSearch: any[] }>();

// 响应式数据
const searchKeyword = ref('');
const selectedSite = ref('');

const subscribeStatus = ref('');
const activeTab = ref<'history' | 'myFilters'>('history')
const PAGE_SIZE = 20
const historyPage = ref(1)
const filtersPage = ref(1)

// 计算属性
const totalSearches = computed(() => {
  return props.historySearch.length + props.recentSearch.length;
});

const subscribedCount = computed(() => {
  const historySubscribed = props.historySearch.filter(item => item.subscribe === '已订阅').length;
  const recentSubscribed = props.recentSearch.filter(item => item.subscribe === '已订阅').length;
  return historySubscribed + recentSubscribed;
});

const latestSearchTime = computed(() => {
  const allSearches = [...props.historySearch, ...props.recentSearch];
  if (allSearches.length === 0) return '暂无';
  
  const latest = allSearches.reduce((latest, current) => {
    return new Date(current.time) > new Date(latest.time) ? current : latest;
  });
  return formatDate(latest.time);
});

const filteredHistorySearch = computed(() => {
  let filtered = props.historySearch;
  
  // 关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  // 站点筛选
  if (selectedSite.value) {
    filtered = filtered.filter(item => 
      item.site === selectedSite.value
    );
  }
  
  // 订阅状态筛选
  if (subscribeStatus.value) {
    filtered = filtered.filter(item => 
      item.subscribe === subscribeStatus.value
    );
  }
  
  return filtered;
});

const filteredRecentSearch = computed(() => {
  let filtered = props.recentSearch;
  
  // 关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.condition.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  

  
  // 订阅状态筛选
  if (subscribeStatus.value) {
    filtered = filtered.filter(item => 
      item.subscribe === subscribeStatus.value
    );
  }
  
  return filtered;
});

// 每页 20 条分页数据
const historyPaged = computed(() => {
  const start = (historyPage.value - 1) * PAGE_SIZE
  return filteredHistorySearch.value.slice(start, start + PAGE_SIZE)
})

const filtersPaged = computed(() => {
  const start = (filtersPage.value - 1) * PAGE_SIZE
  return filteredRecentSearch.value.slice(start, start + PAGE_SIZE)
})

// 方法
function getSiteTagType(site: string) {
  const typeMap: Record<string, string> = {
    'yahoo': 'primary',
    'mercari': 'success',
    'rakuten': 'warning'
  };
  return typeMap[site] || 'info';
}

function getSiteDisplayName(site: string) {
  const nameMap: Record<string, string> = {
    'yahoo': '雅虎闲置',
    'mercari': '煤炉闲置',
    'rakuten': '乐天市场'
  };
  return nameMap[site] || site;
}

function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

function formatTime(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
}

function getTimeAgo(dateString: string) {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) return '今天';
  if (diffDays === 1) return '昨天';
  if (diffDays < 7) return `${diffDays}天前`;
  if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`;
  if (diffDays < 365) return `${Math.floor(diffDays / 30)}个月前`;
  return `${Math.floor(diffDays / 365)}年前`;
}





function exportSearches() {
  ElMessage.success('导出功能开发中...');
}

// 清空记录功能已删除

// 监听筛选变化重置分页
watch([searchKeyword, selectedSite, subscribeStatus], () => {
  historyPage.value = 1
  filtersPage.value = 1
})
</script>

<style scoped>
.search-tab {
  padding: 20px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.3);
}

.stat-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

.stat-icon {
  font-size: 24px;
  opacity: 0.9;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.section-title .el-icon {
  color: #409eff;
}

.section-count {
  font-size: 12px;
  color: #909399;
}

.search-row:hover {
  background-color: #f0f9ff !important;
}

/* 站点信息样式 */
.site-info {
  display: flex;
  align-items: center;
}

/* 关键词信息样式 */
.keyword-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.keyword-text {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}



/* 搜索名称样式 */
.search-name {
  display: flex;
  align-items: center;
}

.name-text {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}



/* 搜索条件样式 */
.condition-info {
  display: flex;
  align-items: center;
}

.condition-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

/* 订阅状态样式 */
.subscribe-status {
  display: flex;
  align-items: center;
}

/* 时间信息样式 */
.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-date {
  font-size: 12px;
  color: #606266;
}

.time-hour {
  font-size: 11px;
  color: #909399;
}

.time-ago {
  font-size: 10px;
  color: #c0c4cc;
  font-style: italic;
}



/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style> 